<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        :root {
            --primary-color: #6cf;
        }

        body {
            color: var(--primary-color);
        }

        .container {
            width: 500px;
            margin: 100px auto;
            text-align: center;
            background-color: beige;
            padding: 50px;
            border-radius: 40px;
            box-shadow: 1px 1px 4px rgba(0, 0, 0, .3);
        }

        .inp {
            width: 80%;
            height: 50px;
            margin-bottom: 10px;
            border: 1px solid var(--primary-color);
            border-radius: 25px;
            padding: 0 20px;
            outline: none;
        }

        .btn {
            border: 0;
            background-color: var(--primary-color);
            width: 150px;
            height: 50px;
            color: #fff;
            font-size: 22px;
            line-height: 50px;
            border-radius: 12px;
        }

        a {
            text-decoration: none;
            font-size: 14px;
            height: 30px;
            color: #666;
        }

        .primary-color {
            color: var(--primary-color);
            font-size: 20px;
        }
    </style>
</head>

<body>
<div class="container">
    <h2>登录</h2>
    <form action="/login" method="post" id="login-form">
        用户名: <input class="inp" id="username" type="text" name="username" autocomplete="off">
        <br>
        密&emsp;码: <input class="inp" id="password" type="password" name="password">
        <br>
        <input class="btn" type="submit" value="登录">
    </form>
    <a href="./register.jsp">没有账户,<span class="primary-color">立即注册</span></a>
</div>

<script>
    let submit = document.querySelector('.btn')
    let username = document.querySelector('#username')
    let password = document.querySelector('#password')
    submit.addEventListener('click', function (e) {
        e.preventDefault()
        if (username.value.trim() === '' || password.value.trim() === '') {
            alert("账户密码没有输入")
            return
        }

        async function login() {
            try {
                let res = await fetch(`/login`,
                    {
                        method: "post",
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: `username=${username.value}&password=${password.value}` // body data type must match "Content-Type" header
                    });
                let data = await res.json();
                if (!data.success) {
                    return alert(data.msg)
                }

                location.href = "./index.jsp"
            } catch (e) {
                console.warn(e)
            }
        }

        login()


    })
</script>

</body>
</html>